package com.max.common.proxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Proxy;
import java.util.Date;
import java.util.Hashtable;

import javax.naming.Context;
import javax.naming.Name;
import javax.naming.NamingException;
import javax.naming.RefAddr;
import javax.naming.Reference;
import javax.naming.spi.ObjectFactory;

import com.max.project.graphics.dao.ContentDao;
import com.max.project.graphics.model.Content;

/**
 * 
 * 项目名称:max-project-graphics
 * 文件名称:ServiceProxyFactory.java
 * 文件描述:
 * 创建人员:chenyibo
 * 创建时间:2013-1-22 下午03:02:25
 * 修改人员:chenyibo
 * 修改时间:2013-1-22 下午03:02:25
 * 修改备注:
 * @version V1.0
 */
public class ServiceProxyFactory implements IServiceProxyFactory, ObjectFactory
{
	private final ClassLoader _loader;
	
	
	public ServiceProxyFactory() 
	{
		this(Thread.currentThread().getContextClassLoader());
	}
	
	public ServiceProxyFactory(ClassLoader _loader) 
	{
		this._loader = _loader;
	}

	@Override
	public <T> T create(Class<T> api)
	{
		return create(api, _loader);
	}
	
	public <T> T create(Class<T> api, ClassLoader loader) 
	{
		if (api == null)
			throw new NullPointerException("api must not be null for ServiceProxyFactory.create()");
		
		InvocationHandler handler = null;
		handler = new LocalPorxyHandler(api);
		Object proxy = Proxy.newProxyInstance(loader,new Class[] {api},handler);
		return (T)proxy;
	}

	@Override
	public Object getObjectInstance(Object obj, Name name, Context nameCtx,
			Hashtable<?, ?> environment) throws Exception 
	{
		Reference ref = (Reference) obj;

	    String api = null;

	    for (int i = 0; i < ref.size(); i++) 
	    {
	    	RefAddr addr = ref.get(i);

	        String type = addr.getType();
	        String value = (String) addr.getContent();

	        if (type.equals("type"))
	        	api = value;
	    }

	    if (api == null)
	    	throw new NamingException("'type' must be configured for ServiceProxyFactory.create()");

	    Class<?> apiClass = Class.forName(api, false, _loader);

	    return create(apiClass);
	}
	
	
	public static void main(String[] args) throws Exception
	{
		ContentDao contentDao = new ServiceProxyFactory().create(ContentDao.class);
		System.out.println(contentDao.count());
		
		System.out.println(contentDao.query(2).getContent());
		System.out.println(contentDao.query(3,8).size());
		
		Content content = new Content();
		content.setName("测试标题");
		content.setContent("测试内容11111");
		content.setCreator("maxchen");
		content.setModifier("maxchen");
		content.setCreate_date(new Date());
		content.setModify_date(new Date());
		System.out.println(contentDao.insert(content));
	}
}
